package cn.sdut.training.utils;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("unchecked")
public class HqlHelper {

	private String selectClause;
	private String fromClause;
	private String whereClause;
	private String orderClause;

	private List<Object> paramList = new ArrayList<Object>();

	/**
	 * 生成FROM子句，别名为this
	 * 
	 * @param entityClass
	 */
	
	public HqlHelper(Class entityClass) {
		fromClause = " FROM " + entityClass.getName() + " this";
	}

	/**
	 * 拼接Select子句
	 * 
	 * @param property
	 * @return
	 */
	public HqlHelper addSelectProperty(String property) {
		if (selectClause == null) { // 查询不重复的属性
			selectClause = "SELECT DISTINCT " + property;
		} else {
			selectClause += ", " + property;
		}
		return this;
	}

	/**
	 * 拼接WHERE子句
	 * 
	 * @param condition
	 * @param params
	 */
	public HqlHelper addWhereCondition(String condition, Object... params) {
		// 拼接WHERE子句
		if (whereClause == null) {
			whereClause = " WHERE " + condition;
		} else {
			whereClause += " AND " + condition;
		}

		// 保存参数
		if (params != null && params.length > 0) {
			for (Object param : params) {
				paramList.add(param);
			}
		}

		return this;
	}

	/**
	 * 拼接ORDER BY子句
	 * 
	 * @param property
	 * @param isAsc
	 */
	public HqlHelper addOrderProperty(String property, boolean isAsc) {
		if (orderClause == null) {
			orderClause = " ORDER BY " + property + (isAsc ? " ASC" : " DESC");
		} else {
			orderClause += ", " + property + (isAsc ? " ASC" : " DESC");
		}

		return this;
	}

	/**
	 * 获取查询数据列表的HQL
	 * 
	 * @return
	 */
	public String getQueryListHql() {
		StringBuffer hql = new StringBuffer();

		// Select
		if (selectClause != null) {
			hql.append(selectClause);
		}

		// Form
		hql.append(fromClause);

		// Where
		if (whereClause != null) {
			hql.append(whereClause);
		}

		// Order
		if (orderClause != null) {
			hql.append(orderClause);
		}

		return hql.toString();
	}

	/**
	 * 获取查询总记录数的HQL
	 * 
	 * @return
	 */
	public String getQueryCountHql() {
		StringBuffer hql = new StringBuffer();

		// Select
		if (selectClause == null) {
			hql.append("SELECT COUNT(*) ");
		} else {
			// Select DISTINCT id,title
			// DISTINCT id,title --> SELECT COUNT( DISTINCT id,title)
			String properties = selectClause.substring("SELECT ".length());
			hql.append("SELECT COUNT(" + properties + ") ");
		}

		// From
		hql.append(fromClause);

		// Where
		if (whereClause != null) {
			hql.append(whereClause);
		}

		// 不需要拼接Order子句

		return hql.toString();
	}

	/**
	 * 获取参数列表
	 * 
	 * @return
	 */
	public List<Object> getParamList() {
		return paramList;
	}

}
